#include "Log.hpp"
#include <arpa/inet.h>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <pthread.h>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include "Thread.hpp"
using namespace LogModule;
using namespace ThreadModule;
int sockfd = 0;
std::string server_ip;
uint16_t server_port = 0;
pthread_t id;
void Send() {
    struct sockaddr_in sockaddr;
    memset(&sockaddr, 0, sizeof(sockaddr));
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_addr.s_addr = inet_addr(server_ip.c_str());
    sockaddr.sin_port = htons(server_port);
    const std::string str = "online";
    int n = sendto(sockfd, str.c_str(), str.size(), 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
    (void)n;
    while (true) {
        std::string in;
        std::cout << "Please Enter# ";
        std::getline(std::cin, in);
        int m = sendto(sockfd, in.c_str(), in.size(), 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
        (void)m;
        if(in == "Quit") {
            pthread_cancel(id);
            break;
        }
    }
}
void Recv() {
    while (1) {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int temp = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
        if(temp > 0) {
            buffer[temp] = '\0';
            std::cerr << buffer << std::endl; // 这里打印在2号描述符 
        }
    }
}
int main(int argc, char* argv[]) {
    if(argc != 3) {
        std::cout << "The Usage is " << argv[0] << " + ip + port" << endl;
        return 1;
    }
    server_ip = argv[1];
    server_port = stoi(argv[2]);
    // 创建套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0) {
        cerr << "socket error" << endl;
        return 1;
    }
    Thread recver(Recv);
    Thread sender(Send);
    recver.Start();
    sender.Start();
    id = recver.Id();
    recver.Join();
    sender.Join();
    return 0;
}